package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Guard;
import cn.wolfcode.crm.domain.OutPay;
import cn.wolfcode.crm.domain.Product;
import cn.wolfcode.crm.mapper.GuardMapper;
import cn.wolfcode.crm.domain.Sales;
import cn.wolfcode.crm.mapper.OutPayMapper;
import cn.wolfcode.crm.mapper.SalesMapper;
import cn.wolfcode.crm.query.OutPayQueryObject;
import cn.wolfcode.crm.service.IOutPayService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class OutPayServiceImpl implements IOutPayService {

    @Autowired
    private OutPayMapper outPayMapper;
    @Autowired
    private SalesMapper salesMapper;
    @Autowired
    private GuardMapper guardMapper;

    @Override
    public void update(OutPay entity) {
        if(entity.getId() != null){
            outPayMapper.update(entity);
            /*将缴费额添加到销售报表*/
            Sales sales = new Sales();
            Guard guard = entity.getGuard();
            sales.setEmployee(guard.getEmployee()); //通过缴费单-->核保单-->开单员工
            sales.setGuard_auditdate(new Date());//缴费时间作为确认收入时间
            sales.setProduct(entity.getProduct());//产品
            sales.setPromise(entity.getPromissgroup().getPromise());//
            sales.setTotalamount(guard.getProduct().getCost());
            salesMapper.insert(sales);
        }

        Guard guard = guardMapper.selectByNum(entity.getGuard().getNum());
        guardMapper.updateState(Guard.COMPLETE_STATE,guard.getId());
        Date overtime = entity.getBeginDate();
        overtime.setYear(overtime.getYear()+ guard.getProduct().getYears());
        guard.setOvertime(overtime);
        guardMapper.updateOvertime(guard);

    }

    @Override
    public PageResult query(OutPayQueryObject qo) {
        int total = outPayMapper.query4Count(qo);
        if(total == 0 ){
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<?> rows = outPayMapper.query4List(qo);
        return new PageResult(total,rows);
    }

}
